﻿using ContactSMS.Client.Models;
using ContactSMS.Client.Response;
using Newtonsoft.Json;
using System.Globalization;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Xml.Linq;

namespace ContactSMS.Client.Service
{
    public class ContactService : BaseService
    {
        HttpClient httpClient;

        public ContactService()
        {
            this.httpClient = new HttpClient();
        }

        public async Task<QResponse<PagedResponse<ContactModel>>> GetContactsAsync(int page = 1, int pageSize = 15)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/Contacts/GetContacts?&page={page}&pageSize={pageSize}";
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            //Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<PagedResponse<ContactModel>>>(resultContent);
            return registerResponse;
        }

        public async Task<QResponse<ContactInfoModel>> GetByIdAsync(long id)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/Contacts/GetById/{id}";
            var response = await httpClient.GetAsync(url);
            response.EnsureSuccessStatusCode();
            var resultContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine(resultContent);
            var registerResponse = JsonConvert.DeserializeObject<QResponse<ContactInfoModel>>(resultContent);
            return registerResponse;
        }

        public async Task<QResponse<ContactInfoModel>> AddContactsAsync(AddContactModel addContactModel)
        {
            var accessToken = await AuthService.GetAccessTokenAsync();
            if (string.IsNullOrEmpty(accessToken))
            {
                throw new InvalidOperationException("Access token is missing. Please log in again.");
            }
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            string url = $"{baseUrl}/api/Contacts/Create";

            var jsonContent = new StringContent(JsonConvert.SerializeObject(addContactModel), Encoding.UTF8, "application/json");

            var response = await httpClient.PostAsync(url, jsonContent);
            if (response.IsSuccessStatusCode)
            {
                var resultContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(resultContent);
                var registerResponse = JsonConvert.DeserializeObject<QResponse<ContactInfoModel>>(resultContent);
                return registerResponse;
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                await Console.Out.WriteLineAsync($"Request failed with status code {response.StatusCode}: {errorContent}");
                return null;
            }
        }
    }
}
